<?php
/**
 * Save & Control Mailbox Configuration 
 * 
 * This page shoudl be called each time the user changes it's email
 * configuration
 * 
 */

use Fox\Generator;
use Fox\Html\Button;
use Fox\Html\Screen;
use Orx\User\MailBox;
use Fox\Popup;

$xview = Xview::instance();
$inlineid = $xview->val('inlineid');
if(!empty($inlineid)) {
	$object = null;
	// Cannot change a mailbox that is not yours
	foreach(User::current()->personalMailers() as $mailer) {
		if($mailer->getInlineId() == $inlineid) {
			$object = $mailer;
			break;
		}
	}
	if(empty($object)) {
		// 
		exit;
	}
} else {
	$object = new \Orx\User\MailBox();
}
$data = $object->getData();

$screen = new Screen('sMailerModify','isave',false,true,Generator::ajaxReload('contentCol'));
$wrapper = $xview->component('messages','configuration'); 
$screen->add($wrapper);
if($data['disable'] == true) {
	$screen->add(new Button('enable'))

		->color(Button::COLOR_GREEN);
} else {
	$screen->add(new Button('disable'))
		->helpMessage(Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::DISABLE_BUTTON_HELP))
		->color(Button::COLOR_RED);
}

$screen->buttonBarClass('text-center');
$screen->initialize($data);
if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			if($object->exists()) {
				if($_POST['pushed'] == 'disable') {
					$fields['disable'] = true;
				} elseif($_POST['pushed'] == 'enable') {
					$fields['disable'] = false;
				}
				$object->setFields($fields);
				$object->update();
				Fox\Message::Success(Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::EMAIL_ACCOUNT_CONFIG_UPDATED,$object->email));
			}
		} catch(Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
	}
	echo $xview->messages(true,true);
	exit;
}
$popup = new Fox\Popup('mCongig',Msg(Orx\Mailer\Messages::BUNDLE,Orx\Mailer\Messages::UPDATE_EMAIL_ACCOUNT_TITLE,$object->email)
				,$screen,600);
echo $popup->display();